import { Add } from 'add-model.js';
var area = require('../../../utils/area')
var p = 0, c = 0, d = 0
var add = new Add();

var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;
var qqmap = new QQMapWX({
  //在腾讯地图开放平台申请密钥 http://lbs.qq.com/mykey.html
  key: 'BJFBZ-ZFTHW-Y2HRO-RL2UZ-M6EC3-GMF4U'
});
Page({
  data: {
    address:[],
    addrId:'',
    current: 0,
    provinceVal: '',
    cityVal: '',
    regionVal: '',
    provinceName: [],
    provinceCode: [],
    provinceSelIndex: '',
    cityName: [],
    cityCode: [],
    citySelIndex: '',
    districtName: [],
    districtCode: [],
    districtSelIndex: '',
    showMessage: false,
    messageContent: '',
    showDistpicker: false,
    info:[]
  },
  formSubmit: function (e) {
    var addr = {};
    
      addr["uaddres_name"] = e.detail.value.realname;
      addr['uaddres_detail'] = e.detail.value.detail;
      addr['uaddres_mobile'] = e.detail.value.mobile;
      addr['uaddres_province'] = this.data.provinceVal;
      addr['uaddres_city'] = this.data.cityVal;
      addr['uaddres_county'] = this.data.regionVal;
      addr['uaddres_id']=this.data.addrId;
      addr['is_default'] = e.detail.value.default ? 1:0;
      
    // 表单验证
      if (e.detail.value.realname== '') {
        wx.showToast({
          title: '请填写收件人'
        });
        return;
      }
      if (!(/^1[34578]\d{9}$/.test(e.detail.value.mobile))) {
        wx.showToast({
          title: '请填写正确手机号码'
        });
        return;
      } 
      if (this.data.provinceVal == '') {
      wx.showToast({
        title: '请输入区域'
      });
      return;
    }
      if (e.detail.value.detail == '') {
      wx.showToast({
        title: '请填写详情地址'
      });
      return;
    }    
   add.addrSubmit(addr, (data) => {
     var pages = getCurrentPages(); //获取加载的页面
     var currentPage = pages[pages.length - 2]; //获取当前页面的对象
    
       if (data['msg']='ok') {
         currentPage.setData({
           addressList: addr,
         });
         console.log(currentPage.data.addressList);
         wx.showToast({
           title: '保存成功',
           duration: 500
         });
         setTimeout(function () {
           wx.navigateBack({
           });
         }, 500);
       }
      // 等待半秒，toast消失后返回上一页
     
   }, function (error) {
     console.log(error);
    });

  },
 
  onLoad: function (options) {
    //判断是否新增或判断
    var  that=this;
    if(options.objectId != undefined) 
    {
      add.getAddress(options.objectId, (data) => {
        console.log(data);
        that.setData({
          address: data,
          provinceVal: data['uaddres_province'],
          cityVal: data['uaddres_city'],
          regionVal: data['uaddres_county'],
        });
      });
      that.setData({
        addrId: options.objectId,
      });
    }
    this.setAreaData()
    //默认框
      //this._loadData();
    // 实例化API核心类
  
  },
  
  abc: function () {
    var that = this
    //用微信提供的api获取经纬度
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        //console.log(res)
        that.setData({ myLatitude: res.latitude - 0.0143, myLongitude: res.longitude - 0.014 })
        //that.loadCity(res.latitude - 0.02185, res.longitude - 0.05328)
        //用腾讯地图的api，根据经纬度获取城市
        qqmap.reverseGeocoder({
          location: {
            latitude: that.data.myLatitude,
            longitude: that.data.myLongitude
          },
          success: function (res) {
            //console.log(res)
            var a = res.result.address_component;
            //获取市和区（区可能为空）
            that.setData({
              provinceVal: a.province,
              cityVal: a.city,
              regionVal: a.district,
            })
            //控制台输出结果
            console.log(that.data.provinceVal)
          }
        })
      }
    })
    console.log(that.data.provinceVal)
  },
  showDistpicker: function () {
    this.setData({
      showDistpicker: true
    })
  },
  distpickerCancel: function () {
    this.setData({
      showDistpicker: false
    })
  },
  distpickerSure: function () {
    this.setData({
      provinceSelIndex: p,
      citySelIndex: c,
      districtSelIndex: d
    })
    this.setData({
      provinceVal: this.data.provinceName[this.data.provinceSelIndex],
      cityVal: this.data.cityName[this.data.citySelIndex],
      regionVal: this.data.districtName[this.data.districtSelIndex],
    })
    console.log(this.data.provinceVal)
    console.log(this.data.cityVal)
    console.log(this.data.regionVal)
    this.distpickerCancel()
  },
  changeArea: function (e) {
    p = e.detail.value[0]
    c = e.detail.value[1]
    d = e.detail.value[2]
    this.setAreaData(p, c, d)
  },
  setAreaData: function (p, c, d) {
    var p = p || 0 // provinceSelIndex
    var c = c || 0 // citySelIndex
    var d = d || 0 // districtSelIndex
    // 设置省的数据
    var province = area['100000']
    var provinceName = [];
    var provinceCode = [];
    for (var item in province) {
      provinceName.push(province[item])
      provinceCode.push(item)
    }
    this.setData({
      provinceName: provinceName,
      provinceCode: provinceCode
    })
    // 设置市的数据
    var city = area[provinceCode[p]]
    var cityName = [];
    var cityCode = [];
    for (var item in city) {
      cityName.push(city[item])
      cityCode.push(item)
    }
    this.setData({
      cityName: cityName,
      cityCode: cityCode
    })
    // 设置区的数据
    var district = area[cityCode[c]]
    var districtName = [];
    var districtCode = [];
    for (var item in district) {
      districtName.push(district[item])
      districtCode.push(item)
    }
    this.setData({
      districtName: districtName,
      districtCode: districtCode
    })
  },
})